const os = require('os')
const net = require('net')

// console.log(net.isIP('192.168.1.1'))

const ifaces = os.networkInterfaces()
// console.log(ifaces)

const exec = require('child_process').exec;
const { resolve } = require('path');
const { rejects } = require('assert');


function arp() {
    const cmd = 'arp -a';

    exec(cmd, function(error, stdout, stderr) {
    // 获取命令执行的输出
    if (error) {
        // console.error(error)
        console.log(stderr);
    } else {
        const lines = stdout.split('\n')
        console.log(lines)
        for(let i=0;i<lines.length;i++) {
            if (lines[i]) {
                const values = lines[i].split(' ')
                console.log('设备名称: %s, ip: %s, mac: %s', values[0], values[1].substring(1, values[1].length-1), values[3]);
            }
        }

    }
    });
}

function ping(ip) {
    return new Promise((resolve, rejects)=>{
        if (ip) {
            let reachable = false
            let ping = require('child_process').spawn('ping',['-c','3',ip]);
            let iconv = require('iconv-lite');
            ping.stdout.on('data',data=>{
                let str = iconv.decode(data,'cp936');
                // console.log(str);
                if (str.indexOf('time=')>0)
                    reachable = true
            })
            ping.stderr.on('data',data=>{
                console.log(data);
                // rejects(data)
            })
            ping.on('close',code=>{
                // console.log('Ping 结束')
                resolve(reachable)
            })
        }
    })
}

async function main() {
    const result = await ping('192.168.88.110')
    console.log(result)
}

main()